package com.wxy.xr.servlet;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.wxy.xr.bean.UploadParams;
import com.wxy.xr.bean.User;
import com.wxy.xr.service.AwardService;
import com.wxy.xr.service.SkillService;
import com.wxy.xr.service.UserService;
import com.wxy.xr.service.WebsiteService;
import com.wxy.xr.service.impl.AwardServiceImpl;
import com.wxy.xr.service.impl.SkillServiceImpl;
import com.wxy.xr.service.impl.WebsiteServiceImpl;
import com.wxy.xr.util.Uploads;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet<User>{
    private SkillService skillService=new SkillServiceImpl();
    private AwardService awardService=new AwardServiceImpl();
    private WebsiteService websiteService=new WebsiteServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri=request.getRequestURI();
        String[] cmps=uri.split("/");
        String methodName = "/"+cmps[cmps.length - 1];

        if(methodName.equals(request.getContextPath())){
            try {
                front(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            super.doGet(request, response);
        }

    }

    public  void admin(HttpServletRequest request, HttpServletResponse response) throws Exception{
        request.setAttribute("user",service.list().get(0));
        forward(request, response,"admin/user.jsp");
    }

    public  void save(HttpServletRequest request, HttpServletResponse response) throws Exception{
        UploadParams params=Uploads.parseRequest(request);
        User user=new User();
        BeanUtils.populate(user, params.getParams());
        //从session中那倒用户名密码
        User loginUser= (User) request.getSession().getAttribute("user");
        user.setEmail(loginUser.getEmail());
        user.setPassword(loginUser.getPassword());
        //处理用户头像
        FileItem item=params.getFileParam("photoFile");
        user.setPhoto(Uploads.uploadImage(item,request,user.getPhoto()));

        if(service.save(user)){
            redirect(request, response,"user/admin");
            request.getSession().setAttribute("user",user);
        }else{
            forward(request, response,"个人信息保存失败");}

    }

    public void password(HttpServletRequest request, HttpServletResponse response)throws Exception{
        forward(request, response,"admin/password.jsp");
    }

    public void updatePassword(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        User user= (User) request.getSession().getAttribute("user");
        if(!user.getPassword().equals(oldPassword)){
            forwardError(request, response,"旧密码不正确");
            return;
        }
        user.setPassword(newPassword);
        if(service.save(user)){
            redirect(request, response,"page/login.jsp");
        }else{
            forward(request, response,"密码修改失败");}

    }
    public  void remove(HttpServletRequest request, HttpServletResponse response) throws Exception{

    }
    public  void login(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setContentType("text/json; charset=UTF-8");
        Map<String,Object> result = new HashMap<>();
        String  captcha=request.getParameter("captcha").toLowerCase();
        String code= (String) request.getSession().getAttribute("code");
        if(!captcha.equals(code)){
            //forwardError(request, response,"验证码不正确");
            result.put("success",false);
            result.put("msg","验证码不正确");
        }else {
            User user=new User();
            BeanUtils.populate(user,request.getParameterMap());
            user=((UserService) service).get(user);
            if(user!=null){
                request.getSession().setAttribute("user",user);
                result.put("success",true);
                //redirect(request, response,"user/admin");
            }else{
                //forwardError(request, response,"邮箱或密码不正确");
                result.put("success",false);
                result.put("msg","邮箱或密码不正确");
            }

        }
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }

    public  void logout(HttpServletRequest request, HttpServletResponse response) throws Exception{
        request.getSession().removeAttribute("user");
        redirect(request, response,"page/login.jsp");
    }
    public  void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //创建验证码对象
        DefaultKaptcha dk=new DefaultKaptcha();
        try(InputStream is=getClass().getClassLoader().getResourceAsStream("kaptcha.properties")) {
            Properties properties=new Properties();
            properties.load(is);
            Config config=new Config(properties);
            dk.setConfig(config);
        }
        //生成验证码字符串
        String code=dk.createText();

        HttpSession session=request.getSession();
        session.setAttribute("code",code.toLowerCase());
        BufferedImage image=dk.createImage(code);
        response.setContentType("image/jpeg");
        //将图片数据写回客户端
        ImageIO.write(image,"jpg",response.getOutputStream());
    }
    public  void front(HttpServletRequest request, HttpServletResponse response) throws Exception{
        User user=service.list().get(0);
        //用户信息
        request.setAttribute("user",user);
        //个人特质
        request.setAttribute("trait",user.getTrait().split(","));
        //兴趣爱好
        request.setAttribute("interests",user.getInterests().split(","));
        //专业技能
        request.setAttribute("skills",skillService.list());
        //获奖成就
        request.setAttribute("awards",awardService.list());
        //网站底部信息
        request.setAttribute("footer",websiteService.list().get(0).getFooter());
        forward(request, response,"front/user.jsp");
    }
}
